Python OrderedDict
π Python's OrderedDict β Order With a Splash of Sassβ
Ever felt like your regular dictionary just didnβt respect the order of things? Like that one coworker who always jumps the lunch queue? Well, say hello to OrderedDict
β the VIP list of dictionaries where order is everything.
Letβs dive into the wild world of OrderedDict
with examples, jokes, and a sprinkle of Pythonic charm.
π― Quick Referenceβ
from collections import OrderedDict
user = OrderedDict(name='sujit', id='100', email='admin@gmail.com')
# Iteration
for key in user:
print(key + ":" + user[key])
# Add a Key at the last
user['location'] = 'India'
# Update a Key
user['email'] = 'admin@fossgurusujit.com'
# Delete a Key
del user['email']
# Pop item from last and start
user.popitem() # from last of dictionary
user.popitem(last=False) # from start of dictionary
# Move item to last and start
user.move_to_end('id') # move to last
user.move_to_end('id', False) # move to start
1. π§ What in the World is an OrderedDict?β
An OrderedDict
is like that super organized friend who remembers everything β in order! Itβs a subclass of dict
that keeps keys in the exact order you shoved them in. Unlike the old-school dict
(pre-3.7), which used to just throw your data around like confetti at a wedding.
β οΈ Keeping order does come at a cost β 50% more memory, but hey, itβs the price of class.
2. π οΈ Creating Your Fancy OrderedDictβ
Letβs summon one from the depths of collections
:
from collections import OrderedDict
π Now create one:
user = OrderedDict()
user['name'] = 'sujit'
user['id'] = 100
user['email'] = 'admin@gmail.com'
print(user)
# OrderedDict([('name', 'sujit'), ('id', 100), ('email', 'admin@gmail.com')])
Or flex your constructor muscles:
user = OrderedDict(name='sujit', id=100, email='admin@gmail.com')
print(user)
# OrderedDict([('name', 'sujit'), ('id', 100), ('email', 'admin@gmail.com')])
π§ Need a default value for multiple keys? fromkeys()
got you:
keys = ['id', 'name', 'email']
user = OrderedDict.fromkeys(keys, 0)
3. π Marching Through an OrderedDict Like a Bossβ
Loop it like a pro, folks:
user = OrderedDict(name='sujit', id="100", email='admin@gmail.com')
# Using keys directly
for key in user:
print(key + ":" + user[key])
for key in user.keys():
print(key + ":" + user[key])
# Using items (because you're fancy)
for key, value in user.items():
print(key + ":" + value)
Output like poetry:
name:sujit
id:100
email:admin@gmail.com
name:sujit
id:100
email:admin@gmail.com
name:sujit
id:100
email:admin@gmail.com
4. βοΈ Add, Zap, and Morph Keys Like a Dict Wizardβ
Because OrderedDict
is mutable, you can do all the usual key sorcery:
user = OrderedDict(name='sujit', id=100, email='admin@gmail.com')
user['location'] = 'India'
print(user)
# OrderedDict([('name', 'sujit'), ('id', 100), ('email', 'admin@gmail.com'), ('location', 'India')])
π§ͺ Updating values wonβt mess up the order:
user['email'] = 'admin@fossgurusujit.com'
ποΈ Delete that key like it never existed:
del user['email']
5. π JSON β Now With Preserved Sassβ
Need that order preserved in JSON too? OrderedDict
wonβt let you down:
from collections import OrderedDict
import json
d = OrderedDict()
d['how'] = 1
d['to'] = 2
d['do'] = 3
d['in'] = 4
d['java'] = 5
json.dumps(d)
# '{"how": 1, "to": 2, "do": 3, "in": 4, "java": 5}'
Even your JSON wears a tuxedo now.
6. βοΈ OrderedDict vs. dict β Letβs Rumbleβ
Letβs settle this showdown:
6.1 π― move_to_end()
β Because Sometimes Keys Need a Vacationβ
Want to move keys around like a boss? You got this.
user = OrderedDict(name='sujit', id="100", email='admin@gmail.com')
user.move_to_end('id')
# Now 'id' is at the end
user.move_to_end('id', False)
# Now 'id' is back at the front
print(user)
# OrderedDict([('id', '100'), ('name', 'sujit'), ('email', 'admin@gmail.com')])
6.2 π§Ή popitem()
β Gentle Kicking Out From Either Endβ
In a regular dict
, popitem()
just tosses the last item. OrderedDict? It gives you options, like a fancy coffee shop.
user = OrderedDict(name='sujit', id="100", email='admin@gmail.com')
print(user.popitem()) # ('email', 'admin@gmail.com')
print(user.popitem(last=False)) # ('name', 'sujit')
7. π Thatβs a Wrapβ
In this whirlwind of a tutorial, youβve learned:
- What an OrderedDict is (fancy!)
- How to create one (with style!)
- How to loop, update, and delete (like a pro!)
- Differences with regular
dict
(OrderedDict wins on class)
Keep your dictionaries classy and in order.
Happy Coding, Pythonistas! ππ»